package com.tbw.service;

import com.tbw.NotFoundException;
import com.tbw.dao.BlogRespository;
import com.tbw.entity.Blog;
import com.tbw.entity.Type;
import com.tbw.util.MarkdownUtils;
import com.tbw.util.MyBeanUtils;
import com.tbw.vo.BlogQuery;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;

import javax.persistence.criteria.*;

import org.springframework.transaction.annotation.Transactional;

import java.util.*;

@Service
public class BlogServiceImpl implements BlogService{

    @Autowired
    private BlogRespository blogRespository;

    @Override
    public Blog getBlog(Long id) {
        return blogRespository.getOne(id);
    }

    @Transactional
    @Override
    public Blog getAndConvertBLog(Long id) {

        Blog blog = blogRespository.getOne(id);
        if (blog==null){
            throw new NotFoundException("该博客不存在");
        }
        Blog b=new Blog();
        //拷貝blog到b
        BeanUtils.copyProperties(blog, b);
        String content = b.getContent();
        //賦值content,處理content,將Markdown转换成HTML
        b.setContent(MarkdownUtils.markdownToHtmlExtensions(content));

        blogRespository.updateViews(id);
        return b;
    }

    @Override
    public Page<Blog> listBlog(Pageable pageable, BlogQuery blog) {
        return blogRespository.findAll(new Specification<Blog>() {
            @Override                   //查询对象         //查询容器                       //条件具体表达式
            public Predicate toPredicate(Root<Blog> root, CriteriaQuery<?> cq, CriteriaBuilder cb) {
                List<Predicate> predicates=new ArrayList<>();
                if (!"".equals(blog.getTitle()) && blog.getTitle()!=null){
                    predicates.add(cb.like(root.<String>get("title"),"%"+blog.getTitle()+"%"));
                }
                if (blog.getTypeId()!=null){
                    predicates.add(cb.equal(root.<Type>get("type").get("id"),blog.getTypeId()));
                }
                if (blog.isRecommend()){
                    predicates.add(cb.equal(root.<Boolean>get("recommend"),blog.isRecommend()));
                }
                cq.where(predicates.toArray(new Predicate[predicates.size()]));
                return null;
            }
        },pageable);
    }

    @Override
    public Page<Blog> listBlog(Long tagId, Pageable pageable) {


        return blogRespository.findAll(new Specification<Blog>() {
            @Override
            public Predicate toPredicate(Root<Blog> root, CriteriaQuery<?> cq, CriteriaBuilder cb) {
                Join join=root.join("tags");
                return cb.equal(join.get("id"),tagId);
            }
        },pageable);
    }

    @Override
    public Page<Blog> listBlog(Pageable pageable) {
        return blogRespository.findAll(pageable);
    }

    @Override
    public Page<Blog> listBlog(String query, Pageable pageable) {


        return blogRespository.findByQuery(query,pageable);
    }

    @Override
    public List<Blog> listRecommendBlogTop(Integer size) {
        Sort sort = Sort.by(Sort.Direction.DESC, "updateTime");
        Pageable pageable = PageRequest.of(0, size, sort);
        return blogRespository.findTop(pageable);
    }

    @Override
    public Map<String, List<Blog>> archiveBlog() {

        List<String> years = blogRespository.findGroupYear();
        Map<String,List<Blog>> map=new HashMap<>();
        for (String year : years){
            map.put(year,blogRespository.findByYear(year));
        }

        return map;
    }

    @Override
    public Long countBlog() {
        return blogRespository.count();
    }

    @Transactional
    @Override
    public Blog saveBlog(Blog blog) {
        if (blog.getId()==null){
            blog.setCreateTime(new Date());
            blog.setUpdateTime(new Date());
            blog.setViews(0);
        }else {
            blog.setUpdateTime(new Date());
        }
        return blogRespository.save(blog);
    }
    /**
     * 根据id修改blog
     *
     * @param blog
     * @return
     */
    @Transactional
    @Override
    public Blog updateBlog(Long id, Blog blog) {
        Blog b = blogRespository.getOne(id);
        if (b == null) {
            throw new NotFoundException("該博客不存在~~~");
        }

        //過濾掉屬性值為空的屬性,只保留有屬性值的blog复制给b,，
        BeanUtils.copyProperties(blog, b, MyBeanUtils.getNullPropertyNames(blog));
        b.setUpdateTime(new Date());
        return blogRespository.save(b);
    }
    @Transactional
    @Override
    public void deleteBlog(Long id) {
        blogRespository.deleteById(id);
    }



}
